/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package vn.ac.aptech.fat1.c0910g.servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import vn.ac.aptech.fat1.c0910g.dao.FoodDAO;
import vn.ac.aptech.fat1.c0910g.dao.MenuDAO;
import vn.ac.aptech.fat1.c0910g.dao.UserDAO;
import vn.ac.aptech.fat1.c0910g.dao.impl.FoodDaoImpl;
import vn.ac.aptech.fat1.c0910g.dao.impl.MenuDaoImpl;
import vn.ac.aptech.fat1.c0910g.dao.impl.UserDaoImpl;
import vn.ac.aptech.fat1.c0910g.entity.Food;
import vn.ac.aptech.fat1.c0910g.entity.Menu;
import vn.ac.aptech.fat1.c0910g.entity.User;
import vn.ac.aptech.fat1.c0910g.util.DBUtility;

/**
 *
 * @author NDC
 */
public class ServiceServlet extends HttpServlet {

    /** 
     * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        String doPara = request.getParameter("do");
        String act = request.getParameter("act");
        try {
            if (doPara != null && doPara.trim().length() > 0) {
                ServletContext context = getServletContext();
                Connection conn = DBUtility.getConnection(context);
                if (doPara.equals("login")) {
                    doLogin(conn, request, response);
                } else if (doPara.equals("logout")) {
                    HttpSession session = request.getSession();
                    session.removeAttribute("user");
                    response.sendRedirect("index.jsp");
                }

                if (act != null && act.trim().length() > 0) {
                    if (act.equals("food")) {
                        FoodDAO foodDAO = new FoodDaoImpl(conn);
                        String name = request.getParameter("txtName");
                        String description = request.getParameter("taDescription");
                        String strPrice = request.getParameter("txtPrice");
                        float price = 0;
                        try {
                            price = Float.parseFloat(strPrice.trim());
                        } catch (Exception ex) {
                        }
                        if (doPara.equals("add")) {
                            Food f = new Food();
                            f.setName(name.trim());
                            f.setDescription(description.trim());
                            f.setPrice(price);
                            boolean b = foodDAO.addFood(f);
                            if (b) {
                                response.sendRedirect("?style=management&act=food");
                            }
                        } else if (doPara.equals("edit")) {
                            String strId = request.getParameter("txtId");
                            int id = 0;
                            try {
                                id = Integer.parseInt(strId);
                            } catch (Exception ex) {
                                //
                            }
                            Food f = new Food();
                            f.setId(id);
                            f.setName(name.trim());
                            f.setDescription(description.trim());
                            f.setPrice(price);
                            boolean b = foodDAO.updateFood(f);
                            if (b) {
                                response.sendRedirect("?style=management&act=food");
                            }
                        } else if (doPara.equals("update")) {
                        } else if (doPara.equals("delete")) {
                            String strId = request.getParameter("id");
                            int id = 0;
                            try {
                                id = Integer.parseInt(strId);
                            } catch (Exception ex) {
                                //
                            }
                            Food f = new Food();
                            f.setId(id);
                            boolean b = foodDAO.deleteFood(f);
                            if (b) {
                                response.sendRedirect("?style=management&act=food");
                            }
                        }
                    } else if (act.equals("menu")) {
                        MenuDAO menuDAO = new MenuDaoImpl(conn);
                        String name = request.getParameter("txtName");
                        String description = request.getParameter("taDescription");
                        if (doPara.equals("add")) {
                            Menu menu = new Menu();
                            menu.setName(name.trim());
                            menu.setDescription(description.trim());
                            boolean b = menuDAO.addMenu(menu);
                            if (b) {
                                response.sendRedirect("?style=management&act=menu");
                            }
                        } else if (doPara.equals("edit")) {
                            String strId = request.getParameter("txtId");
                            int id = 0;
                            try {
                                id = Integer.parseInt(strId.trim());
                            } catch (Exception ex) {
                                //
                            }
                            Menu menu = new Menu();
                            menu.setId(id);
                            menu.setName(name.trim());
                            menu.setDescription(description.trim());
                            boolean b = menuDAO.updateMenu(menu);
                            if (b) {
                                response.sendRedirect("?style=management&act=menu");
                            }
                        } else if (doPara.equals("update")) {
                            String strId = request.getParameter("txtIdMenu");
                            int menuId = 0;
                            int foodId = 0;
                            try {
                                menuId = Integer.parseInt(strId.trim());
                            } catch (Exception ex) {
                                //
                            }
                            strId = request.getParameter("foodList");
                            try {
                                foodId = Integer.parseInt(strId.trim());
                            } catch (Exception ex) {
                                //
                            }
                            Menu m = new Menu();
                            m.setId(menuId);
                            Food f = new Food();
                            f.setId(foodId);
                            boolean b = false;
                            if (!menuDAO.checkFood(m, f)) {
                                b = menuDAO.addFoodToMenu(m, f);
                            }
                            response.sendRedirect("?style=detail&act=menu&id=" + menuId);
                        } else if (doPara.equals("delete")) {
                            String strId = request.getParameter("id");
                            int id = 0;
                            try {
                                id = Integer.parseInt(strId);
                            } catch (Exception ex) {
                                //
                            }
                            Menu menu = new Menu();
                            menu.setId(id);
                            boolean b = menuDAO.deleteMenu(menu);
                            if (b) {
                                response.sendRedirect("?style=management&act=menu");
                            }
                        } else if (doPara.equals("remove")) {
                            String strId = request.getParameter("mid");
                            int menuId = 0;
                            int foodId = 0;
                            try {
                                menuId = Integer.parseInt(strId.trim());
                            } catch (Exception ex) {
                                //
                            }
                            strId = request.getParameter("fid");
                            try {
                                foodId = Integer.parseInt(strId.trim());
                            } catch (Exception ex) {
                                //
                            }
                            Menu m = new Menu();
                            m.setId(menuId);
                            Food f = new Food();
                            f.setId(foodId);                            
                            boolean b = menuDAO.removeFoodFromMenu(m, f);                            
                            response.sendRedirect("?style=detail&act=menu&id=" + menuId);
                        }
                    }
                }
                DBUtility.closeConnection(conn);
            }
        } catch (Exception ex) {
            ex.printStackTrace();
            out.println("<html>");
            out.println("<head>");
            out.println("<title>Error!!!</title>");
            out.println("</head>");
            out.println("<body>");
            out.println("<h1>Oops! Have some errors!</h1>");
            out.println(ex.getMessage());
            out.println("</body>");
            out.println("</html>");
        } finally {
            out.close();
        }
    }

    void doLogin(Connection conn, HttpServletRequest request, HttpServletResponse response)
            throws Exception {
        String username = request.getParameter("txtUsername");
        String password = request.getParameter("txtPassword");
        String remember = request.getParameter("chkRemember");
        boolean isLogin = false;
        if (username != null && password != null) {
            UserDAO userDAO = new UserDaoImpl(conn);
            User user = userDAO.doLogin(username, password);
            if (user != null) {
                HttpSession session = request.getSession();
                session.setAttribute("user", user);
                if (remember != null && remember.equals("on")) {
                    Cookie usernameCookie = new Cookie("username", username);
                    usernameCookie.setMaxAge(2 * 24 * 3600);
                    Cookie passwordCookie = new Cookie("password", password);
                    passwordCookie.setMaxAge(2 * 24 * 3600);
                    response.addCookie(usernameCookie);
                    response.addCookie(passwordCookie);
                }
                isLogin = true;
            }
        }
        response.sendRedirect(isLogin ? "index.jsp" : "index.jsp?style=login");
    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /** 
     * Handles the HTTP <code>GET</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /** 
     * Handles the HTTP <code>POST</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /** 
     * Returns a short description of the servlet.
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>
}
